﻿/*
Copyright (c) 2010 Lance Ward
This software is licensed under the MIT license, except where otherwise noted.
For complete license details, refer to license.txt
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ADNColorPicker
{
	public class HexEdit : TextBox
	{
		public HexEdit()
		{
			//disable default context menu
			this.ContextMenu = new ContextMenu();
			this.MaxLength = 6;
		}

		public Color Color
		{
			get { return HexToColor(this.Text); }
			set { this.Text = ColorToHex(value); }
		}

		public event EventHandler ColorChanged;	//a mirror of GradientRange color changed

		private void OnColorChanged()
		{
			if (ColorChanged != null) { ColorChanged(this, EventArgs.Empty); }
		}

		protected override void OnKeyPress(KeyPressEventArgs e)
		{
			string hexChars = new string(hexDigits);
			string keyChar = e.KeyChar.ToString().ToUpper();

			if (!hexChars.Contains(keyChar) && e.KeyChar != (char)Keys.Back)
			{
				e.Handled = true;
			}
			else
			{
				OnColorChanged();
			}

			base.OnKeyPress(e);
		}
		//override paste.
		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if (keyData == (Keys.Control | Keys.V))
			{
				OnColorChanged();
			}

			return base.ProcessCmdKey(ref msg, keyData);
		}

		protected override void OnLostFocus(EventArgs e)
		{
			this.Text = this.Text.ToUpper();
			base.OnLostFocus(e);
		}
		static char[] hexDigits = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

		private string ColorToHex(Color c)
		{
			byte[] bytes = new byte[3];
			bytes[0] = c.R;
			bytes[1] = c.G;
			bytes[2] = c.B;
			char[] chars = new char[bytes.Length * 2];
			for (int i = 0; i < bytes.Length; i++)
			{
				int b = bytes[i];
				chars[i * 2] = hexDigits[b >> 4];
				chars[i * 2 + 1] = hexDigits[b & 0xF];
			}
			return new string(chars);
		}

		private Color HexToColor(string hex)
		{
			//remove anything that's not 0-9, A-F, including #
			//parse as 00 00 00 - it should be exactly 6 characters long 
			// R G B
			//convert to upper before translating

			return Color.White;
		}
	}
}
